import {Link, useNavigate} from 'react-router-dom'
import {Card, Breadcrumb, Form, Button, Radio, DatePicker, Select, Popconfirm} from 'antd'
import locale from 'antd/es/date-picker/locale/zh_CN'
import { Table, Tag, Space } from 'antd'
import { EditOutlined, DeleteOutlined } from '@ant-design/icons'
import img404 from "../../assets/error.png"
import {useChannel} from "../../hooks/useChannel.jsx";
import {useEffect, useState} from "react";
import {deleteArticleAPI, getArticleListAPI} from "../../apis/article.jsx";
import dayjs from "dayjs";


const { Option } = Select
const { RangePicker } = DatePicker

const Article = () => {
    const navigate = useNavigate()
    const { channelList } =useChannel()
    // 准备列数据
    const columns = [
        {
            title: '封面',
            dataIndex: 'cover_url',
            width: 120,
            render: (CoverUrl) => {
                const coverURLs = CoverUrl ? CoverUrl.split(',') : [];
                const coverURL = coverURLs[0] || img404; // 如果没有封面 URL，使用占位图
                return <img
                    src={coverURL}
                    width={80}
                    height={60}
                    alt="封面"
                    style={{objectFit: 'cover'}} // 确保图片适配容器大小
                />
            }
        },
        {
            title: '标题',
            dataIndex: 'title',
            width: 220
        },
        {
            title: '状态',
            dataIndex: 'draft',
            render: draft => {
                const statusMap = {
                    false : { text: '已发布', color: 'orange' },
                    true: { text: '草稿', color: 'green' }
                }
                return <Tag color={statusMap[draft]?.color || 'gray'}>{statusMap[draft]?.text || '未知状态'}</Tag>
            }
        },
        {
            title: '更新时间',
            dataIndex: 'UpdatedAt',
            render: date => {
                return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
            }
        },
        {
            title: '阅读数',
            dataIndex: 'read_count'
        },
        {
            title: '评论数',
            dataIndex: 'comment_count'
        },
        {
            title: '点赞数',
            dataIndex: 'like_count'
        },
        {
            title: '收藏数',
            dataIndex: 'star_count'
        },
        {
            title: '操作',
            render: data => {
                return (
                    <Space size="middle">
                        <Button type="primary" shape="circle" icon={<EditOutlined />} onClick={() => navigate(`/layout/publish?id=${data.ID}`)}  />
                        <Popconfirm title={"删除文章"}
                                    description={"确认要删除文章吗？"}
                                    okText="确定"
                                    cancelText="取消"
                                    onConfirm={()=>onConfirm(data)}>
                            <Button
                            type="primary"
                            danger
                            shape="circle"
                            icon={<DeleteOutlined />}
                        /></Popconfirm>

                    </Space>
                )
            }
        }
    ]

    const onConfirm= async (data)=> {
        console.log('OK',data)
        await deleteArticleAPI(data.ID)
        setReqData({
            ...reqData
        })
    }
// 准备表格body数据

    // 获取文章列表
    const [list, setList] = useState()
    const [total, setTotal] = useState()
    const [ reqData, setReqData] = useState({
        status : 2,
        channelId : 0,
        beginPubDate : '',
        endPubDate : '',
        page : 1,
        pageSize : 10
    })
    const onFinish = async (formValues) => {
        console.log("formValues:", formValues)
        setReqData({
            ...reqData,
            channelId: formValues.channel_id,
            status: formValues.status,
            beginPubDate: formValues.date?.[0]?.format('YYYY-MM-DD HH:mm:ss') || '',
            endPubDate: formValues.date?.[1]?.format('YYYY-MM-DD HH:mm:ss') || '',
        })
    }
    useEffect(() => {
        async function getArticleList() {
            const res = await getArticleListAPI( reqData )
            setList(res.data.data)
            setTotal(res.data.total)
            console.log(res.data)
        }
        getArticleList()
    },[reqData])
    return (
        <div>
            <Card
                title={
                    <Breadcrumb items={[
                        { title: <Link to={'/'}>首页</Link> },
                        { title: '文章列表' },
                    ]} />
                }
                style={{ marginBottom: 20 }}
            >
                <Form initialValues={{ status: 2 }} onFinish={onFinish}>
                    <Form.Item label="状态" name="status">
                        <Radio.Group>
                            <Radio value={2}>全部</Radio>
                            <Radio value={0}>草稿</Radio>
                            <Radio value={1}>审核通过</Radio>
                        </Radio.Group>
                    </Form.Item>

                    <Form.Item label="频道" name="channel_id">
                        <Select
                            placeholder="请选择文章频道"
                            style={{ width: 120 }}
                        >
                            <Option key={"all"} value={0}>全部频道</Option>
                            {channelList.map(item => <Option key={item.ID} value={item.ID}>{item.name}</Option>)}
                        </Select>
                    </Form.Item>

                    <Form.Item label="日期" name="date">
                        {/* 传入locale属性 控制中文显示*/}
                        <RangePicker locale={locale}></RangePicker>
                    </Form.Item>

                    <Form.Item>
                        <Button type="primary" htmlType="submit" style={{ marginLeft: 40 }}>
                            筛选
                        </Button>
                    </Form.Item>
                </Form>
            </Card>
            {/*        */}
            <Card>
                <Table rowKey="ID"
                       columns={columns}
                       dataSource={list}
                       pagination={{
                           total,
                           showTotal: (total) => `共${total}条`,
                           onChange: (page) => {
                               setReqData({
                                   ...reqData,
                                   page: page
                               })
                           }
                       }}
                />
            </Card>
        </div>

    )
}

export default Article